package com.hsurosy.trigger.job;

import cn.bugstack.middleware.db.router.strategy.IDBRouterStrategy;
import com.hsurosy.domain.task.model.entity.TaskEntity;
import com.hsurosy.domain.task.service.ITaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author Hsu琛君珩
 * @Date 2024-11-15 14:04
 * @Description 发送MQ消息任务队列
 * @Version: v1.0.0
 */
@Slf4j
@Component()
public class SendMessageTaskJob {

    @Resource
    private ITaskService taskService; // 任务服务接口，用于操作任务相关逻辑
    @Resource
    private ThreadPoolExecutor executor; // 线程池，用于并发执行消息发送任务
    @Resource
    private IDBRouterStrategy dbRouter; // 数据库路由策略，用于分库分表

    /**
     * 定时扫描第一个库的MQ消息任务表
     */
    @Scheduled(cron = "0/5 * * * * ?")
    public void exec_db01() {
        try {
            // 设置数据库路由，指向第一个库的任务表
            dbRouter.setDBKey(1);
            dbRouter.setTBKey(0);
            // 查询未发送的消息任务列表
            List<TaskEntity> taskEntities = taskService.queryNoSendMessageTaskList();
            if (taskEntities.isEmpty()) return;
            // 发送MQ消息
            for (TaskEntity taskEntity : taskEntities) {
                try {
                    taskService.sendMessage(taskEntity); // 发送消息
                    taskService.updateTaskSendMessageCompleted(taskEntity.getUserId(), taskEntity.getMessageId());
                } catch (Exception e) {
                    log.error("定时任务，发送MQ消息失败 userId: {} topic: {}", taskEntity.getUserId(), taskEntity.getTopic());
                    taskService.updateTaskSendMessageFail(taskEntity.getUserId(), taskEntity.getMessageId());
                }
            }
        } catch (Exception e) {
            log.error("定时任务，扫描MQ任务表发送消息失败。", e);
        } finally {
            dbRouter.clear();
        }
    }

    /**
     * 定时扫描第二个库的MQ消息任务表
     */
    @Scheduled(cron = "0/5 * * * * ?")
    public void exec_db02() {
        try {
            // 设置数据库路由，指向第二个库的任务表
            dbRouter.setDBKey(2);
            dbRouter.setTBKey(0);
            // 查询未发送的消息任务列表
            List<TaskEntity> taskEntities = taskService.queryNoSendMessageTaskList();
            if (taskEntities.isEmpty()) return;
            // 发送MQ消息
            for (TaskEntity taskEntity : taskEntities) {
                try {
                    taskService.sendMessage(taskEntity); // 发送消息
                    taskService.updateTaskSendMessageCompleted(taskEntity.getUserId(), taskEntity.getMessageId());
                } catch (Exception e) {
                    log.error("定时任务，发送MQ消息失败 userId: {} topic: {}", taskEntity.getUserId(), taskEntity.getTopic());
                    taskService.updateTaskSendMessageFail(taskEntity.getUserId(), taskEntity.getMessageId());
                }
            }
        } catch (Exception e) {
            log.error("定时任务，扫描MQ任务表发送消息失败。", e);
        } finally {
            dbRouter.clear();
        }
    }

}
